//
//  WSNewsViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/23.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSNewsViewController.h"
#import "WSNewsDetailViewController.h"

#import "WSNewsSelectionTableCell.h"
#import "WSNewsHeader.h"
#import "WSBannerView.h"

#import "NewsService.h"
#import "WSNewsInfo.h"
#import "WSBannerInfo.h"

static NSString *CellID = @"NewsCell";
@interface WSNewsViewController ()<UITableViewDataSource, UITableViewDelegate>
// 资讯列表视图
@property (nonatomic, strong) UITableView *newsTable;
// 顶部广告视图
@property (nonatomic, strong) WSBannerView *topBanner;
// table view 头部视图
@property (nonatomic, strong) WSNewsHeader *newsHeader;

// data source
@property (nonatomic, strong) NSArray <WSBannerInfo *> *topBannerDatas; // 广告
@property (nonatomic, strong) NSArray <WSNewsInfo *> *newsList; // 资讯

// 顶部资讯id
@property (nonatomic, copy) NSString *topArticle_id;

// 资讯分页
@property (nonatomic, assign) NSInteger pageNo;

@end

@implementation WSNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self ws_setup];
    [self ws_addSubviews];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
//    self.newsHeader.xmg_height = self.newsHeader.height;
}

- (void)ws_setup {
    WEAKSELF
    [self.newsTable mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
        weakSelf.pageNo = 1;
        [weakSelf ws_loadData];
    }];
    [self.newsTable.mj_header beginRefreshing];
}

- (void)ws_addSubviews {
    self.newsTable.tableHeaderView = self.newsHeader;
    self.newsTable.tableFooterView = [UIView new];
    [self.view addSubview:self.newsTable];
}

- (void)ws_loadData {
    dispatch_group_t group = dispatch_group_create();
    
    // 获取资讯首页
    dispatch_group_enter(group);
    [NewsService fetchNewsDataWithResult:^(id  _Nonnull responseObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
        if (!response.data) {
            dispatch_group_leave(group);
            return;
        }
        // 广告
        self.topBannerDatas = [NSArray yy_modelArrayWithClass:[WSBannerInfo class] json:response.data[@"banner"]];
        self.newsHeader.banners = self.topBannerDatas;
        
        // 顶部资讯
        WSNewsInfo *topNewsinfo = [WSNewsInfo yy_modelWithJSON:response.data[@"top_article"]];
        self.topArticle_id = topNewsinfo.article_id;
        self.newsHeader.newsInfo = topNewsinfo;
        self.newsHeader.xmg_height = self.newsHeader.height;
        
        dispatch_group_leave(group);
    }];
    
    
    // 获取资讯列表
    dispatch_group_enter(group);
    [NewsService fetchNewsListWithPage:_pageNo callback:^(id  _Nonnull resObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:resObj];
        if (!response.data) {
            dispatch_group_leave(group);
            return;
        }

        self.newsList = [NSArray yy_modelArrayWithClass:[WSNewsInfo class] json:response.data[@"data"]];
        
        dispatch_group_leave(group);
    }];
    
    
    // request complete
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.newsTable reloadData];
        [self.newsTable.mj_header endRefreshing];
    });
}


#pragma mark - UITableViewDataSouce, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.newsList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSNewsSelectionTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[WSNewsSelectionTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    WSNewsSelectionTableCell *newsCell = (WSNewsSelectionTableCell *)cell;
    newsCell.newsInfo = self.newsList[indexPath.row];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.topArticle_id = self.newsList[indexPath.row].article_id;
    [self performSegueWithIdentifier:@"NewsDetail" sender:nil];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0 ) {
        UIView *header = [UIView new];
        header.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = @"今日精选";
        titleLabel.textColor = kFontColorBlack;
        titleLabel.font = WSFontMake(15);
        [header addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12.f);
            make.centerY.offset(0.f);
        }];
        
        UIView *bottomLine = [UIView new];
        bottomLine.backgroundColor = kSeparatorColor;
        [header addSubview:bottomLine];
        
        [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(10.f);
            make.right.offset(-10.f);
            make.height.offset(0.5f);
            make.bottom.offset(0.f);
        }];
        
        return header;
        
    } else {
        return [UIView new];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 44.f : 0.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 135.f;
}



#pragma mark - Getters

- (UITableView *)newsTable {
    if (_newsTable == nil) {
        _newsTable = [[UITableView alloc] initWithFrame:CGRectMake(0, kTopHeight, kMainScreenWidth, kMainScreenHeight-kTopHeight-kTabBarHeight) style:UITableViewStyleGrouped];
        _newsTable.backgroundColor = kCommonBackgroudColor;
        _newsTable.scrollIndicatorInsets = UIEdgeInsetsMake(self.newsHeader.xmg_height, 0, 0, 0);
        _newsTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _newsTable.delegate = self;
        _newsTable.dataSource = self;
        [_newsTable registerClass:[WSNewsSelectionTableCell class] forCellReuseIdentifier:CellID];
    }
    return _newsTable;
}

- (WSNewsHeader *)newsHeader {
    if (_newsHeader == nil) {
        
        _newsHeader = [WSNewsHeader viewFromXib];
        
        // 跳转资讯详情
        WEAKSELF
        _newsHeader.didTapViewCallback = ^{
            [weakSelf performSegueWithIdentifier:@"NewsDetail" sender:nil];
        };
    }
    return _newsHeader;
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"NewsDetail"]) {
        WSNewsDetailViewController *detailVc = (WSNewsDetailViewController *)segue.destinationViewController;
        detailVc.articleId = self.topArticle_id;
    }
}


@end
